package cn.biwysh.exam.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.biwysh.exam.biz.ZhiShiBiz;
import cn.biwysh.exam.entity.Knowledge;

public class Download extends HttpServlet {

	
	@SuppressWarnings("deprecation")
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html; charset=utf-8");
		String id = request.getParameter("id");
		if (id != null) {
			ZhiShiBiz biz=new ZhiShiBiz();
			Knowledge model = biz.GetKnowledgeById(Integer.valueOf(id));
			if(model!=null){
				if(model.getType()!=0){
					response.setHeader("Content-Disposition", "attachment;filename="
							+ URLEncoder.encode(model.getFilename().substring(model.getFilename().lastIndexOf("@@")+2),"utf-8"));
					response.setHeader("Connection", "close");
					response.setHeader("Content-Type", "application/octet-stream");
					String filepath=request.getRealPath("upload/konwledge/")+"\\"+model.getFilename();
					 OutputStream outp = null;
				     FileInputStream in = null;
					try
				      {
				          outp = response.getOutputStream();
				          in = new FileInputStream(filepath);

				          byte[] b = new byte[1024];
				          int i = 0;

				          while((i = in.read(b)) > 0)
				          {
				              outp.write(b, 0, i);
				          }
				          outp.flush();
				      }
				      catch(Exception e)
				      {
				          System.out.println("Error!");
				          //e.printStackTrace();
				      }
				      finally
				      {
				          if(in != null)
				          {
				              in.close();
				              in = null;
				          }
				          if(outp != null)
				          {
				              outp.close();
				              outp = null;
				          }
				      }
				}
			}
			
		}
		
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);
	}

}
